package cn.com.callback

import cn.com.kh.KHUtil;
import groovy.json.*;
import groovy.swing.impl.DefaultAction
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.DateFormat
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import cn.com.elite.Util;

/**
 *
 * @Title: ApiBPCreate* @Description:深圳宝安排水系统工单录入同步接口--外部接口
 * @author: chieh* @date 2020-11-08 21:28:00
 *
 */

public class ApiBPCreate implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ApiBPCreate.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }
        long startTime = System.currentTimeMillis();

        String reJson = null;
        long endTime = 0;

        JSONArray resArray = new JSONArray();
        JSONObject resObject = new JSONObject();

        //生成随机36位id
        String Relation_ID = UUID.randomUUID().toString();
        log.debug("objective_guid:" + Relation_ID);

        //生成小程序工单编号
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        Calendar calendar = Calendar.getInstance();
        String workorderid = "W" + df.format(calendar.getTime());
        log.debug("生成小程序工单编号:" + workorderid);

        try {
            // 调用处理信息
            JSONObject inObject = new JSONObject(inData);
            log.debug("处理前的Json：" + inObject.toString());

            String openid = KHUtil.GetJV(inObject, "openid");//openid

            String companytpye = KHUtil.GetJV(inObject, "companytpye");//单位类别
            String business1 = KHUtil.GetJV(inObject, "business1");//业务类型
            String business2 = KHUtil.GetJV(inObject, "business2");//水务设施
            String business3 = KHUtil.GetJV(inObject, "business3");//投诉内容
            String isstreet = KHUtil.GetJV(inObject, "isstreet");//行政街道
            String address = KHUtil.GetJV(inObject, "address");//详细地址
            String description = KHUtil.GetJV(inObject, "description");//问题描述

            String locationy = KHUtil.GetJV(inObject, "locationx");//X坐标
            String locationx = KHUtil.GetJV(inObject, "locationy");//Y坐标

            String att = KHUtil.GetJV(inObject, "att");//图片
            log.debug("解析信息-companytpye：" + companytpye + " business1：" + business1 + " business2：" + business2 + " business3：" + business3 + " isstreet：" + isstreet + " address：" + address + " description：" + description + " locationx：" + locationx + " locationy：" + locationy + " att" + att);

            //必填项校验
            String dealMessage = KHUtil.isNullMSG("openid", openid) + KHUtil.isNullMSG("business1", business1) + KHUtil.isNullMSG("business2", business2) + KHUtil.isNullMSG("description", description) + KHUtil.isNullMSG("att", att);

            if (!KHUtil.isNull(dealMessage)) {
                endTime = System.currentTimeMillis();
                log.warn(dealMessage);
                reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + dealMessage + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;

            } else {
                String rec_Guid = "MP-" + KHUtil.getRandomString(33);
                //处理附件图片
                JSONArray arrJsonArray = new JSONArray(att);
                int arrInt = arrJsonArray.length();
                log.debug("接入图片数量:" + arrInt);
                String uploadArr = "";
                for (int i = 0; i < arrInt; i++) {
                    JSONObject arrJson = arrJsonArray.getJSONObject(i);
                    //图片信息
                    String url = KHUtil.GetJV(arrJson, "url");//附件的 URL
                    String filename = KHUtil.GetJV(arrJson, "filename");//文件名称，路径
                    log.debug("附件名称:" + filename);
                    log.debug("附件URL:" + url);

                    String updateSQL = "Insert Into Uploadlist (Uploadguid, Createdate, Path, Filename, Filedesc, Staff_Id, Guid, Customer_Guid, Confidential_Type, Upload_Status, Examine_Type, Uploadlist_Guid) Values (uuid(), now(), ?, ?, ?, 'SYSTEM', ?, ?, 1, 0, '小程序', uuid())";
                    def urlresult = jt.update(updateSQL, url, filename, filename, rec_Guid, openid);
                    log.debug("图片更新sql结果:" + urlresult);

                    uploadArr = KHUtil.isNull(uploadArr) ? url : uploadArr + ";" + url;
                }

                //处理客户
                String selectSQL = "Select Customer_Guid, Customername, Mobile As Mobile From Customer Where Wechatid = ? Order By Createddate Asc";
                List<Map<String, Object>> customerresult = jt.queryForList(selectSQL, openid);

                log.debug("查看客户是否存在sql结果:" + customerresult);
                String old_customer_guid = null;
                String customername = null;
                String mobile = null;
                if (customerresult.size() > 0) {
                    old_customer_guid = customerresult.get(0).get("Customer_Guid");
                    customername = customerresult.get(0).get("Customername");
                    mobile = customerresult.get(0).get("Mobile");
                } else {
                    endTime = System.currentTimeMillis();
                    reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(当前账号无授权注册！),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    return reJson;
                }

                //处理工单
                String dataSQL = "Insert Into Wx_Uploads_List (Rec_Guid, Open_Id, Level_Id1, Level_Id2, Level_Id3, Level_Id4, Level_Id5, Level_Id6, Locationx, Locationy, Comments, Upload_Arr, Create_Time) Values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, Now())";
                def dataresult = jt.update(dataSQL, rec_Guid, openid, workorderid, business1, business2, business3, isstreet, address, locationx, locationy, description, uploadArr);

                log.debug("当前执行更新结果SQL结果:" + dataresult.toString());
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"创单成功处理失败,请检查确认入参有效且合法\"}";

        }

        resObject.put("workorderid", workorderid);
        resArray.put(resObject);

        endTime = System.currentTimeMillis();
        outData = "{\"resultcode\":\"1\",\"resultmessage\":\"创单成功处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray + "}";
        return outData;
    }

    /**
     * 坐标转换，腾讯地图转换成百度地图坐标
     *
     * @param lat 腾讯纬度
     * @param lon 腾讯经度
     * @return 返回结果：经度,纬度
     */
    public static String map_tx2bd(String a, String b) {
        double bd_lat;
        double bd_lon;
        double x_pi = 3.14159265358979324;

        double x = Double.valueOf(a);
        double y = Double.valueOf(b);
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        bd_lon = z * Math.cos(theta) + 0.0065;
        bd_lat = z * Math.sin(theta) + 0.006;

        System.out.println("bd_lat:" + bd_lat);
        System.out.println("bd_lon:" + bd_lon);
        return bd_lon + "," + bd_lat;
    }

}